import requests


class NBLogin:
    def __init__(self):
        self.session = requests.session()
        self.authurl = 'https://login-uat.digitalvolvo.com/oauth2/auth?client_id=3a1ef6bc-60f1-430b-ac96-b3a60ee70bb3&scope=openid&response_type=code&redirect_uri=https://newbie-uat.digitalvolvo.com/static/auth.html&state=123456789'
        self.loginurl = 'https://login-uat.digitalvolvo.com/api/midend/auth/login'
        self.tokenurl = 'https://mse-uat.digitalvolvo.com/api/dmscus.login/auth/callback'

    def authLogin(self):
        return self.session.get(url=self.authurl, allow_redirects=False)

    def login(self):
        response = self.authLogin().headers.get('Location')
        print(response)
        login_challenge = response[response.index('=') + 1:]
        print(login_challenge)
        data = {"login_challenge": login_challenge, "_csrf": "", "username": "ZMAO5",
                "password": "Maomao1234567"}
        response = self.session.post(url=self.loginurl,data=data)
        response = response.history[3].headers.get('Location')
        print(response)
        response = response[response.index('code') + 5:-39]
        return response
    def tokenLogin(self):
        code = self.login()
        data1 = {"code":code}
        response = self.session.get(url = self.tokenurl,params=data1)
        r1 = response.json().get('data').get('access_token')
        Authorization = "Bearer " + r1
        return Authorization


if __name__ == '__main__':
    print(NBLogin().tokenLogin())




